'use strict';
const Controller = require('egg').Controller;
class shelfController extends Controller {
  /**
   * 接口描述：书架列表
   * 请求方式：get
   * 参数：{
   *
   *  }
   */
  async list() {
    const { ctx, app } = this;
    const token = ctx.request.header.authorization;
    const user = await ctx.service.user.get({
      token,
    });
    const data = await app.mysql.query(`SELECT * FROM book_shelf WHERE userId=${user.userId}`);
    const list = [];
    await new Promise(succ => {
      (async () => {
        if (data.length > 0) {
          for (let i = 0; i < data.length; i++) {
            const item = await app.mysql.get('books', { bookId: data[i].bookId });
            list.push({
              ...item,
              ...data[i],
            });
            if (i === data.length - 1) { succ(); }
          }
        } else {
          succ();
        }

      })();
    });
    ctx.body = {
      code: 200,
      data: list,
      msg: '',
    };
  }

  async add() {
    const { ctx, app } = this;
    const body = ctx.request.body;
    const bookId = body.bookId;
    if (!bookId) {
      app.throwError(400, 'bookId不能为空');
    }
    const progressDirectoryId = body.progressDirectoryId;
    const token = ctx.request.header.authorization;
    const user = await ctx.service.user.get({
      token,
    });

    const isHas = await app.mysql.select('book_shelf', { where: { bookId } });
    console.log(isHas);
    if (isHas.length === 0) {
      const result = await app.mysql.insert('book_shelf', {
        userId: user.userId,
        bookId,
        progressDirectoryId,
        updateTime: new Date().getTime(),
      });
      if (result.affectedRows !== 1) {
        app.throwError(500, '数据库插入失败');
      }
    } else {
      const result = await app.mysql.update('book_shelf', {
        progressDirectoryId,
        updateTime: new Date().getTime(),
      }, {
        where: {
          bookId,
        },
      });
      if (result.affectedRows !== 1) {
        app.throwError(500, '修改数据库错误');
      }
    }


    ctx.body = {
      code: 200,
      data: '',
      msg: '',
    };
  }
}

module.exports = shelfController;
